import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { FindOneOptions, Repository } from 'typeorm';
import { DeepPartial } from 'typeorm/common/DeepPartial';
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import { Result } from '../vo/result';

@Injectable()
export abstract class MysqlBaseService<T> {
  protected constructor(protected repository: Repository<T>) {}

  async findAll() {
    return this.repository.find();
  }

  // 查找某一个. FindOneOptions类型
  async findOne(options: FindOneOptions<T>) {
    const result = await this.repository.findOne(options);
    if (result) {
      return result;
    } else {
      throw new HttpException('用户未找到', HttpStatus.NOT_FOUND);
    }
  }
  // DeepPartial 可选的可有可无
  async create(createDto: DeepPartial<T>) {
    // create this.repository.save(createDto)  并不是保存用户数据的意思，而是创建一个实体的意思
    // const entity = this.repository.create(createDto);
    // return await this.repository.save(entity);

    // update 只能更新
    // save可以实现插入和更新，如果传入给他的对象有id则会更新，如果没有id则会保存插入
    return await this.repository.save(createDto);
  }
  // 更新
  async update(id: number, updateDto: QueryDeepPartialEntity<T>) {
    const result = await this.repository.update(id, updateDto);
    if (result.affected) {
      return Result.success('用户更新成功');
    } else {
      throw new HttpException('用户未更新成功', HttpStatus.NOT_FOUND);
    }
  }

  // 删除
  async delete(id: number) {
    const result = await this.repository.delete(id);
    if (result.affected) {
      return Result.success('删除用户成功');
    } else {
      throw new HttpException('用户未删除成功', HttpStatus.NOT_FOUND);
    }
  }
}
